﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QualityStormCommon;
using System.Web.Security;
using Role = QualityStormCommon.Role;


namespace QualityStorm {
    public partial class FrmUsers : Form {

        User m_user;

        ConnectionContextBag m_contextBag;

        bool m_PasswordWasChanged=false;
        bool m_ReadOnly=false;

        public bool ReadOnly {
            get {
                return m_ReadOnly;
            }
            set {
                m_ReadOnly = true;
                SetReadOnly();
            }
        }

        private void SetReadOnly() {
            txtTelephone.Enabled = !m_ReadOnly;
            lblTelephone.Enabled = !m_ReadOnly;
            txtEmail.Enabled = !m_ReadOnly;
            lblEmail.Enabled = !m_ReadOnly;
            txtPassword.Enabled = !m_ReadOnly;
            lblPassword.Enabled = !m_ReadOnly;
            txtLogin.Enabled = !m_ReadOnly;
            lblLogin.Enabled = !m_ReadOnly;
            txtLastName.Enabled = !m_ReadOnly;
            lblLastName.Enabled = !m_ReadOnly;
            txtFirstName.Enabled = !m_ReadOnly;
            lblFirstName.Enabled = !m_ReadOnly;
            txtCellPhone.Enabled = !m_ReadOnly;
            lblCellPhone.Enabled = !m_ReadOnly;
            nudNumberOfTrials.Enabled = !m_ReadOnly;
            lblMaxNumberOfTrials.Enabled = !m_ReadOnly;
            chkLockedOut.Enabled = !m_ReadOnly;
            lblDays.Enabled = !m_ReadOnly;
            nudPasswordExpiration.Enabled = !m_ReadOnly;
            chkPasswordExpires.Enabled = !m_ReadOnly;
            lblLastLogin.Enabled = !m_ReadOnly;
            lblRoles.Enabled = !m_ReadOnly;
            btnOK.Enabled = !m_ReadOnly;
            lstRoles.Enabled = !m_ReadOnly;
            chkMustChangePassword.Enabled = !m_ReadOnly;

        }

        public ConnectionContextBag ContextBag {
            get {
                return m_contextBag;
            }
            set {
                m_contextBag = value;
            }
        }

        public User User {
            get {
                return m_user;
            }
            set {
                m_user = value;
                ShowData();
            }
        }

        private void ShowData() {
            if (m_user != null) {
                txtFirstName.Text = m_user.FirstName;
                txtLastName.Text = m_user.LastName;
                txtLogin.Enabled = false;
                txtLogin.Text = m_user.Login;
                txtPassword.Text = "pwdplaceholder";
                txtEmail.Text = m_user.Email;
                txtTelephone.Text = m_user.Telephone;
                txtCellPhone.Text = m_user.CellPhone;
                chkLockedOut.Checked = (bool)m_user.LockedOut;
                nudNumberOfTrials.Value = (int)m_user.MaxNumberOfTrials;
                chkPasswordExpires.Checked = (bool)m_user.PasswordExpires;
                nudPasswordExpiration.Value = (int)m_user.PasswordExpirationDays;
                chkMustChangePassword.Checked = (bool)m_user.MustChangePassword;

                lblLastLogin.Text = "Last login: " + m_user.LastLogin.ToString();
                lstRoles.Items.Clear();

                Role[] roles = ContextBag.Context.Service.GetRoles();
                Role[] userRoles = ContextBag.Context.Service.GetUserRoles(m_user);
                foreach (Role role in roles) {
                    try {
                        lstRoles.Items.Add(role.Name, userRoles.Contains(role, new RoleComparer()));
                    } catch {
                    }
                }

            } else {
                txtPassword.Text = "pwdplaceholder";
                lblLastLogin.Text = "Last Login: New user";
                Role[] roles = ContextBag.Context.Service.GetRoles();
                foreach (Role role in roles) {

                    lstRoles.Items.Add(role.Name);
                }
            }

        }

        public FrmUsers() {
            InitializeComponent();
        }

        public FrmUsers(ConnectionContextBag bag) {
            m_contextBag = bag;
            InitializeComponent();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e) {

        }

      


        private void btnOK_Click(object sender, EventArgs e) {
            if (txtFirstName.Text == "") {
                MessageBox.Show("Please inform the user's Name.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            if (txtLogin.Text == "") {
                MessageBox.Show("Please inform the user's Login.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            bool Adding = m_user == null;
            try {
                if (Adding) {
                    if (!m_PasswordWasChanged) {
                        MessageBox.Show("Please inform a password.", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return;
                    }

                    m_user = User.CreateUser(Guid.NewGuid());

                } 

                if (m_PasswordWasChanged) {
                    FrmChangePassword frm = new FrmChangePassword();
                    frm.Password = txtPassword.Text;
                    frm.ShowDialog();
                    if (frm.DialogResult == DialogResult.OK) {
                        m_user.Password= FormsAuthentication.HashPasswordForStoringInConfigFile(frm.Password, "SHA1");
                    } else {
                        return;
                    }

                }


                m_user.FirstName = txtFirstName.Text;
                m_user.LastName=txtLastName.Text;
                if (ContextBag.Folder == null) {
                    m_user.Parent = ContextBag.Module.Guid;
                } else {
                    m_user.Parent = ContextBag.Folder.Guid;
                }


                

                m_user.Login = txtLogin.Text;
                m_user.Email = txtEmail.Text;
                m_user.Telephone = txtTelephone.Text;
                m_user.CellPhone = txtCellPhone.Text;
                m_user.LockedOut = chkLockedOut.Checked;
                m_user.MaxNumberOfTrials = (byte)nudNumberOfTrials.Value;
                m_user.PasswordExpires = chkPasswordExpires.Checked;
                m_user.PasswordExpirationDays = (byte)nudPasswordExpiration.Value;
                m_user.MustChangePassword = chkMustChangePassword.Checked;


                for (int i = 0; i < lstRoles.Items.Count; i++) {
                    string roleName = lstRoles.Items[i].ToString();
                    bool chk = lstRoles.GetItemChecked(i);

                    ContextBag.Context.Service.SetRoleToUser(roleName, m_user, chk);



                }

                if (Adding) {
                    ContextBag.Context.Service.AddUser(m_user);
                    ContextBag.Context.Service.SaveChanges();
                } else {
                    ContextBag.Context.Service.UpdateUser(m_user);
                }




                DialogResult = DialogResult.OK;
                Close();

            } catch (ObjectAlreadyCreatedException oace) {
                MessageBox.Show("There is already a User with this Login!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void FrmUser_Load(object sender, EventArgs e) {
            txtFirstName.Focus();
        }

        private void nudNumberOfTrials_ValueChanged(object sender, EventArgs e) {

        }

        private void chkPasswordExpires_CheckedChanged(object sender, EventArgs e) {
            nudPasswordExpiration.Enabled = chkPasswordExpires.Checked;
        }

        private void txtPassword_Enter(object sender, EventArgs e) {
            txtPassword.SelectAll();
        }

        private void txtPassword_TextChanged(object sender, EventArgs e) {
            if (txtPassword.Text != "pwdplaceholder") 
            m_PasswordWasChanged = true;
        }

     
    }
    class RoleComparer : IEqualityComparer<Role> {
      

        #region IEqualityComparer<Role> Members

        public bool Equals(Role x, Role y) {
            return x.Guid==y.Guid;
        }

        public int GetHashCode(Role obj) {
            return obj.Name.GetHashCode();
        }

        #endregion
    }

    
}
